﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.WindowsAzure.StorageClient;

namespace CPlase
{
    public class EntityURL
    {
        public EntityURL() { }
        public EntityURL(string Table, string PartitionKey, string RowKey)
        {
            this.Table = Table;
            this.PartitionKey = PartitionKey;
            this.RowKey = RowKey;
        }

        public string Table;
        public string PartitionKey;
        public string RowKey;

        public T LoadEntity<T>(TableServiceContext Context) where T : TableServiceEntity
        {
            var Query = Context.CreateQuery<T>(Table);
            var Item = (from p in Query where p.PartitionKey == PartitionKey && p.RowKey == RowKey select p).First<T>();
            return Item;
        }
    }

    public class EntitesURL : List<EntityURL>
    {
        public string Serialize()
        {
            return BlobUtils.Serialize<EntitesURL>(this);
        }

        public static EntitesURL Deserialize(string Serialized)
        {
            return BlobUtils.Deserialize<EntitesURL>(Serialized);
        }
    }

    public class EntityLink : TableServiceEntity { }

    public static class StorageTable
    {
        public static bool Delete(EntityURL Entity, TableServiceContext Context = null)
        {
            //TODO: Удаление без загрузки сущьности
            try
            {
                bool IsContextCreated = Context == null;
                if (IsContextCreated) Context = Azure.GetContext();
                var Item = Entity.LoadEntity<EntityLink>(Context);
                Context.DeleteObject(Item);
                if (IsContextCreated) Context.SaveChanges();
                return true;
            }
            catch { return false; }
        }

        public static bool Delete(EntitesURL Entites, TableServiceContext Context = null)
        {
            //TODO: Удаление без загрузки сущьностей
            try
            {
                bool IsContextCreated = Context == null;
                if (IsContextCreated) Context = Azure.GetContext();
                foreach (var Entity in Entites)
                {
                    var Item = Entity.LoadEntity<EntityLink>(Context);
                    Context.DeleteObject(Item);
                }
                if (IsContextCreated) Context.SaveChanges();
                return true;
            }
            catch { return false; }
        }
    }

}